package com.zhongli.devplatform.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.util.Date;


@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {


    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;



    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/.well-known/pki-validation/**").addResourceLocations("classpath:/static/.well-known/pki-validation/");
    }

    @PostConstruct
    public void initEditableAvlidation() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
        if (initializer.getConversionService() != null) {
            GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
            genericConversionService.addConverter(new Converter<String, Date>() {
                @Override
                public Date convert(String s) {
                    if (StringUtils.isBlank(s)) {
                        return null;
                    }
                    try {
                        return DateUtils.parseDate(s, "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd");
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            });

        }
    }


//    @Bean
//    public RestTemplate restTemplate(
//            @Value("${spring.rest-template.connect-timeout}") int connectTimeout, @Value("${spring.rest-template.read-timeout}") int readTimeout) {
//        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
//        requestFactory.setConnectTimeout(connectTimeout);
//        requestFactory.setReadTimeout(readTimeout);
//
//        RestTemplate restTemplate = new RestTemplate(requestFactory);
//        return restTemplate;
//    }


}
